﻿package com.jacky.utils 
{
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;

	/**
	 * ListenerProxy 事件管理器
	 * @author 	Martin
	 * @qq 		183654371
	 * @msn 	im@mococo.cn
	 */
	
	public class ListenerProxy
	{
		private var listeners:Dictionary = new Dictionary(false);
		
		public function ListenerProxy() 
		{
			
		}
		
		public function addListener($target:IEventDispatcher, $type:String, $listener:Function, $useCapture:Boolean = false, $priority:int = 0, $useWeakReference:Boolean = false)
		{
			if ( !listeners[$target] ) listeners[$target] = [];
			listeners[$target].push([$type,$listener,$useCapture,$priority,$useWeakReference]);
			$target.addEventListener($type,$listener,$useCapture,$priority,$useWeakReference);
		}
		
		public function removeTargetListener($target:IEventDispatcher):void
		{
			if ( !listeners[$target] ) return;
			var listener:Array = listeners[$target];
			var params:Array;
			while ( listener.length > 0 )
			{
				params = listener.pop();
				if ( $target.hasEventListener(params[0]) ) $target.removeEventListener(params[0],params[1],params[2]);
			}
			listeners[$target] = null;
			delete listeners[$target];
		}
		
		public function removeListeners():void
		{
			if ( listeners )
			{
				for ( var i:* in listeners )
				{
					removeTargetListener(i);
					listeners[i] = null;
					delete listeners[i];
				}
			}
		}
		
		public function destory():void
		{
			removeListeners();
			listeners = null;
		}
	}

}